package org.jeecg.modules.business.controller;

import java.math.BigDecimal;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.business.entity.*;
import org.jeecg.modules.business.enums.AgreementCommonEnum;
import org.jeecg.modules.business.enums.CommissionTypeEnum;
import org.jeecg.modules.business.enums.CommissionUnitEnum;
import org.jeecg.modules.business.service.IBusMarketAgreementCustomerHousePriceService;
import org.jeecg.modules.business.service.IBusMarketAgreementCustomerService;
import org.jeecg.modules.business.vo.AgreementCustomerHousePriceVo;
import org.jeecg.modules.rooms.entity.CesRoomLayout;
import org.jeecg.modules.rooms.mapper.CesRoomLayoutMapper;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 协议单位-客户协议
 * @Author: jeecg-boot
 * @Date:   2023-04-11
 * @Version: V1.0
 */
@Api(tags="协议单位-客户协议")
@RestController
@RequestMapping("/business/busMarketAgreementCustomer")
@Slf4j
public class BusMarketAgreementCustomerController extends JeecgController<BusMarketAgreementCustomer, IBusMarketAgreementCustomerService> {
	@Autowired
	private IBusMarketAgreementCustomerService busMarketAgreementCustomerService;

//	 @Autowired
//	 private IBusMarketAgreementCustomerHousePriceService busMarketAgreementCustomerHousePriceService;
//
//	 @Resource
//	 private CesRoomLayoutMapper cesRoomLayoutMapper;
	/**
	 * 分页列表查询
	 *
	 * @param busMarketAgreementCustomer
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "协议单位-客户协议-分页列表查询")
	@ApiOperation(value="协议单位-客户协议-分页列表查询", notes="协议单位-客户协议-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BusMarketAgreementCustomer>> queryPageList(BusMarketAgreementCustomer busMarketAgreementCustomer,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BusMarketAgreementCustomer> queryWrapper = QueryGenerator.initQueryWrapper(busMarketAgreementCustomer, req.getParameterMap());
		Page<BusMarketAgreementCustomer> page = new Page<BusMarketAgreementCustomer>(pageNo, pageSize);
		IPage<BusMarketAgreementCustomer> pageList = busMarketAgreementCustomerService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 /**
	  * 列表查询
	  *
	  * @param busMarketAgreementCustomer
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "协议单位-客户协议-列表查询")
	 @ApiOperation(value="协议单位-客户协议-列表查询", notes="协议单位-客户协议-列表查询")
	 @GetMapping(value = "/queryList")
	 public Result<List<BusMarketAgreementCustomer>> queryList(BusMarketAgreementCustomer busMarketAgreementCustomer, HttpServletRequest req) {
		 QueryWrapper<BusMarketAgreementCustomer> queryWrapper = QueryGenerator.initQueryWrapper(busMarketAgreementCustomer, req.getParameterMap());
		 LoginUser user = TokenUtils.getAuthUser();
		 if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
			 queryWrapper.eq("tenant_id",user.getRelTenantIds());
		 }
		 queryWrapper.eq("del_flag",0);
		 List<BusMarketAgreementCustomer> list = busMarketAgreementCustomerService.list(queryWrapper);
		 return Result.OK(list);
	 }
	 String _tenantId = "";
	/**
	 *   添加
	 *
	 * @param busMarketAgreementCustomer
	 * @return
	 */
	@AutoLog(value = "协议单位-客户协议-添加")
	@ApiOperation(value="协议单位-客户协议-添加", notes="协议单位-客户协议-添加")
	//@RequiresPermissions("business:bus_market_agreement_customer_info:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BusMarketAgreementCustomer busMarketAgreementCustomer) {
		busMarketAgreementCustomer.setDelFlag(CommonConstant.DEL_FLAG_0);
		LoginUser user = TokenUtils.getAuthUser();
		if(busMarketAgreementCustomer.getTenantId() == null || busMarketAgreementCustomer.getTenantId().equals("")){
			if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
				busMarketAgreementCustomer.setTenantId(user.getRelTenantIds());
			} else {
				throw new JeecgBootException("当前登录人租户信息错误");
			}
		}
		//协议单号校验
		LambdaQueryWrapper<BusMarketAgreementCustomer> queryWrapper = new LambdaQueryWrapper<BusMarketAgreementCustomer>();
		queryWrapper.eq(BusMarketAgreementCustomer::getNumber,busMarketAgreementCustomer.getNumber());
		if (StringUtils.isNotBlank(busMarketAgreementCustomer.getId())) {
			// 编辑页面校验
			queryWrapper.ne(BusMarketAgreementCustomer::getId,busMarketAgreementCustomer.getId());
		}
		long num = busMarketAgreementCustomerService.count(queryWrapper);
		if (num != 0) {
			// 该值不可用
			return Result.error("协议单号已存在！");
		}
		busMarketAgreementCustomer.setRoomType(CommissionTypeEnum.house.getKey());
		busMarketAgreementCustomer.setCommission(AgreementCommonEnum.yes.getKey());
		busMarketAgreementCustomer.setFixedDiscount(AgreementCommonEnum.yes.getKey());
		busMarketAgreementCustomer.setDiscount(BigDecimal.valueOf(100));
		busMarketAgreementCustomerService.saveCustomer(busMarketAgreementCustomer,user.getRelTenantIds());

//		busMarketAgreementCustomerService.save(busMarketAgreementCustomer);
//		//客户协议添加完成后，处理关联的房价信息
//		// 获取到所有房型
//		List<CesRoomLayout> layoutList = cesRoomLayoutMapper.selectList(new QueryWrapper<CesRoomLayout>()
//				.eq(CesRoomLayout.HOTEL_ID, busMarketAgreementCustomer.getHotelId())
//				.eq(CesRoomLayout.INVALID,false));
//		List<BusMarketAgreementCustomerHousePrice> customerHousePriceList = new ArrayList<>();
//		if (layoutList != null && layoutList.size() >0) {
//			LoginUser user = TokenUtils.getAuthUser();
//			if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
//				_tenantId = user.getRelTenantIds();
//			}
//			layoutList.forEach(item -> {
//				BusMarketAgreementCustomerHousePrice customerHousePrice = new BusMarketAgreementCustomerHousePrice();
//				customerHousePrice.setCustomerId(busMarketAgreementCustomer.getId());
//				customerHousePrice.setLayoutId(item.getId());
//				customerHousePrice.setAgreementPrice(item.getMarketPrice());
//				customerHousePrice.setAgreementDiscount(BigDecimal.valueOf(100));
//				customerHousePrice.setAgreementDiscount(BigDecimal.valueOf(100));
//				customerHousePrice.setBreakfastNumber(0);
//				customerHousePrice.setMonthPrice(BigDecimal.valueOf(0));
//				customerHousePrice.setCommissionUnit(CommissionUnitEnum.yuan.getKey());
//				customerHousePrice.setDailyCommission(BigDecimal.valueOf(0));
//				customerHousePrice.setDelFlag(CommonConstant.DEL_FLAG_0);
//				customerHousePriceList.add(customerHousePrice);
//			});
//			busMarketAgreementCustomerHousePriceService.saveBatch(customerHousePriceList);
//		}
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param busMarketAgreementCustomer
	 * @return
	 */
	@AutoLog(value = "协议单位-客户协议-编辑")
	@ApiOperation(value="协议单位-客户协议-编辑", notes="协议单位-客户协议-编辑")
	//@RequiresPermissions("business:bus_market_agreement_customer_info:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BusMarketAgreementCustomer busMarketAgreementCustomer) {
//		busMarketAgreementCustomerService.updateById(busMarketAgreementCustomer);
		LoginUser user = TokenUtils.getAuthUser();
		if(busMarketAgreementCustomer.getTenantId() == null || busMarketAgreementCustomer.getTenantId().equals("")){
			if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
				busMarketAgreementCustomer.setTenantId(user.getRelTenantIds());
			} else {
				throw new JeecgBootException("当前登录人租户信息错误");
			}
		}
		//协议单号校验
		LambdaQueryWrapper<BusMarketAgreementCustomer> queryWrapper = new LambdaQueryWrapper<BusMarketAgreementCustomer>();
		queryWrapper.eq(BusMarketAgreementCustomer::getNumber,busMarketAgreementCustomer.getNumber());
		if (StringUtils.isNotBlank(busMarketAgreementCustomer.getId())) {
			// 编辑页面校验
			queryWrapper.ne(BusMarketAgreementCustomer::getId,busMarketAgreementCustomer.getId());
		}
		long num = busMarketAgreementCustomerService.count(queryWrapper);
		if (num != 0) {
			// 该值不可用
			return Result.error("协议单号已存在！");
		}
		BusMarketAgreementCustomer editModel = busMarketAgreementCustomerService.getById(busMarketAgreementCustomer.getId());
		editModel.setName(busMarketAgreementCustomer.getName());
		editModel.setType(busMarketAgreementCustomer.getType());
		editModel.setNumber(busMarketAgreementCustomer.getNumber());
		editModel.setSignTime(busMarketAgreementCustomer.getSignTime());
		editModel.setEffective(busMarketAgreementCustomer.getEffective());
		editModel.setSecrecy(busMarketAgreementCustomer.getSecrecy());
		editModel.setCustomerSignatory(busMarketAgreementCustomer.getCustomerSignatory());
		editModel.setCompanySignatory(busMarketAgreementCustomer.getCompanySignatory());
		editModel.setRemarks(busMarketAgreementCustomer.getRemarks());
		editModel.setContent(busMarketAgreementCustomer.getContent());
		busMarketAgreementCustomerService.updateById(editModel);
		return Result.OK("编辑成功!");
	}

	 /**
	  *  编辑
	  *
	  * @param agreementCustomerHousePriceVo
	  * @return
	  */
	 @AutoLog(value = "客户协议房价-编辑")
	 @ApiOperation(value="客户协议房价-编辑", notes="客户协议房价-编辑")
	 @RequestMapping(value = "/editHousePrice", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> editHousePrice(@RequestBody AgreementCustomerHousePriceVo agreementCustomerHousePriceVo) {
		 LoginUser user = TokenUtils.getAuthUser();
		 BusMarketAgreementCustomer busMarketAgreementCustomer = agreementCustomerHousePriceVo.getAgreementCustomer();
		 if(busMarketAgreementCustomer.getTenantId() == null || busMarketAgreementCustomer.getTenantId().equals("")){
			 if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
				 busMarketAgreementCustomer.setTenantId(user.getRelTenantIds());
			 } else {
				 throw new JeecgBootException("当前登录人租户信息错误");
			 }
		 }
		 BusMarketAgreementCustomer editModel = busMarketAgreementCustomerService.getById(busMarketAgreementCustomer.getId());
		 editModel.setRoomType(busMarketAgreementCustomer.getRoomType());
		 editModel.setCommissionUnit(busMarketAgreementCustomer.getCommissionUnit());
		 editModel.setDailyCommission(busMarketAgreementCustomer.getDailyCommission());
		 editModel.setCommission(busMarketAgreementCustomer.getCommission());
		 editModel.setFixedDiscount(busMarketAgreementCustomer.getFixedDiscount());
		 editModel.setDiscount(busMarketAgreementCustomer.getDiscount());
		 //协议房价信息处理
		 List<BusMarketAgreementCustomerHousePrice> customerHousePriceList = agreementCustomerHousePriceVo.getCustomerHousePriceList();
		 busMarketAgreementCustomerService.editCustomer(editModel,customerHousePriceList);
		 return Result.OK("编辑成功!");
	 }

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "协议单位-客户协议-通过id删除")
	@ApiOperation(value="协议单位-客户协议-通过id删除", notes="协议单位-客户协议-通过id删除")
	//@RequiresPermissions("business:bus_market_agreement_customer_info:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		busMarketAgreementCustomerService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "协议单位-客户协议-批量删除")
	@ApiOperation(value="协议单位-客户协议-批量删除", notes="协议单位-客户协议-批量删除")
	//@RequiresPermissions("business:bus_market_agreement_customer_info:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.busMarketAgreementCustomerService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "协议单位-客户协议-通过id查询")
	@ApiOperation(value="协议单位-客户协议-通过id查询", notes="协议单位-客户协议-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BusMarketAgreementCustomer> queryById(@RequestParam(name="id",required=true) String id) {
		BusMarketAgreementCustomer busMarketAgreementCustomer = busMarketAgreementCustomerService.getById(id);
		if(busMarketAgreementCustomer==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(busMarketAgreementCustomer);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param busMarketAgreementCustomer
    */
    //@RequiresPermissions("business:bus_market_agreement_customer_info:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BusMarketAgreementCustomer busMarketAgreementCustomer) {
        return super.exportXls(request, busMarketAgreementCustomer, BusMarketAgreementCustomer.class, "协议单位-客户协议");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("business:bus_market_agreement_customer_info:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BusMarketAgreementCustomer.class);
    }

}
